package com.lagou.utils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author Roger
 * @date 2020/8/15 9:17
 * @description
 */
@Component("transactionManager")
@Aspect
public class TransactionManager {

    @Autowired
    private ConnectionUtil connectionUtil;




    @Around("execution(* com.lagou.service.impl.AccountServicecImpl.transfer(..))")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) {
        Object proceed = null;
        try {
            startTransaction();
            proceed = proceedingJoinPoint.proceed();
            commit();
        } catch (Throwable throwable) {
            rollBack();
            throwable.printStackTrace();
        } finally {
            release();
        }
        return proceed;
    }


    public void startTransaction() {
        Connection connection = connectionUtil.getConnection();
        try {
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void commit() {
        try {
            connectionUtil.getConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void rollBack() {
        try {
            connectionUtil.getConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void release() {
        try {
            connectionUtil.getConnection().setAutoCommit(true);
            connectionUtil.getConnection().close();
            connectionUtil.removeThreadConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


}
